package mogo.sisdemo;

import java.util.HashSet;
import java.util.Set;

import sisdroid.framework.model.Net;
import android.content.Context;
import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.util.Config;
import android.util.Log;

public class SimpleCompass implements sisdroid.framework.sensors.Sensor
{
	
	int currentDirection = -1; // Default to invalid!
	
	private final SensorListener mListener = new SensorListener()
	{
		
		public void onSensorChanged(int sensor, float[] values)
		{
				
			
				Log.d("SimpleCompass", "Heading (" + values[0] + ")" );
				
				int iNewOrintation = -1;
				float wherelooking = values[ 0 ]; 
				if ( wherelooking < 45 )
				{
					iNewOrintation = DirectionChanged.N;
				}
				else if ( wherelooking < ( 90 + 45 ) )
				{
					iNewOrintation = DirectionChanged.W;
				}
				else if ( wherelooking < ( 90 + 90 + 45 ) )
				{
					iNewOrintation = DirectionChanged.S;
				}
				else if ( wherelooking < ( 90 + 90 + 90 + 45 ) )
				{
					iNewOrintation = DirectionChanged.E;
				}
				else if ( wherelooking < 361 )
				{
					iNewOrintation = DirectionChanged.N;
				}
				if ( iNewOrintation != currentDirection )
				{
					currentDirection = iNewOrintation;
					_observer.newDirection( currentDirection );
				}
				
				
		}

	        public void onAccuracyChanged(int sensor, int accuracy)
	        {
	            // TODO Auto-generated method stub
	            
	        }
	    };
	
	public interface DirectionChanged
	{
		public static final int N	= 0;
		public static final int W	= 1;
		public static final int S	= 2;
		public static final int E	= 3;
		
		void newDirection( int iNewDirection );
		
	}
	
	DirectionChanged _observer;
	SensorManager SensorManager;
	
	public SimpleCompass( Context c )
	{
		
		
		_observer = new DirectionChanged()
		{
			@Override
			public void newDirection(int iNewDirection)
			{
				 Log.d("SimpleCompass", "Looking at (" + iNewDirection + ")" );
				
			}
		};
		
		SensorManager = (SensorManager) c.getSystemService( Context.SENSOR_SERVICE );
		
        SensorManager.registerListener( mListener, 
        		SensorManager.SENSOR_ORIENTATION,
        		SensorManager.SENSOR_DELAY_GAME);
		
	}

	@Override
	public Set<Net> getNetIDS()
	{
		Set<Net> data = new HashSet<Net>();
		
		if ( this.currentDirection != -1 )
		{
			String heading = null;
			switch ( this.currentDirection )
			{
				case DirectionChanged.N: heading = "North"; break;
				case DirectionChanged.E: heading = "East"; break;
				case DirectionChanged.S: heading = "South"; break;
				default: heading = "West"; break;
			}
			data.add( new Net("SimpleCompass", heading ) );
		}
		return data;
	}

}
